<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="124px">
      <div style="height: 100px;overflow: hidden scroll;">
        <el-button type="primary" @click="showSelectSetting = true">
          搜索条件配置
        </el-button>
        <el-form-item v-if="isShowSearch('storeName')" label="店铺" prop="storeName">
          <el-select v-model="queryParams.storeName" filterable placeholder="请选择店铺" clearable >
            <el-option
              v-for="item in storeList"
              :key="item.id"
              :label="item.storeName"
              :value="item.storeName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="isShowSearch('statDate')" label="统计日期" prop="statDate">
          <el-date-picker
            v-model="queryParams.statDateRange"
            @change="statDateChange"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item v-if="isShowSearch('successGoodsRefundAmount')" label="成功退货退款金额" prop="successGoodsRefundAmount">
          <el-input v-model="queryParams.successGoodsRefundAmountMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.successGoodsRefundAmountMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('payAmount')" label="支付金额" prop="payAmount">
          <el-input v-model="queryParams.payAmountMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.payAmountMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('payQuantity')" label="支付件数" prop="payQuantity">
          <el-input v-model="queryParams.payQuantityMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.payQuantityMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('goodsAddPeopleNumber')" label="商品加购人数" prop="goodsAddPeopleNumber">
          <el-input v-model="queryParams.goodsAddPeopleNumberMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.goodsAddPeopleNumberMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('goodsAddQuantity')" label="商品加购件数" prop="goodsAddQuantity">
          <el-input v-model="queryParams.goodsAddQuantityMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.goodsAddQuantityMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('goodsVisitorNumber')" label="商品访客数" prop="goodsVisitorNumber">
          <el-input v-model="queryParams.goodsVisitorNumberMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.goodsVisitorNumberMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('goodsCollectPeopleNumber')" label="商品收藏人数" prop="goodsCollectPeopleNumber">
          <el-input v-model="queryParams.goodsCollectPeopleNumberMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.goodsCollectPeopleNumberMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('goodsStopDuration')" label="商品平均停留时长" prop="goodsStopDuration">
          <el-input v-model="queryParams.goodsStopDurationMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.goodsStopDurationMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('payBuyNumber')" label="支付买家数" prop="payBuyNumber">
          <el-input v-model="queryParams.payBuyNumberMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.payBuyNumberMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('goodsDetailDapRate')" label="商品详情页跳出率" prop="goodsDetailDapRate">
          <el-input v-model="queryParams.goodsDetailDapRateMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.goodsDetailDapRateMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('payOldBuyNumber')" label="支付老买家数" prop="payOldBuyNumber">
          <el-input v-model="queryParams.payOldBuyNumberMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.payOldBuyNumberMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('oldBuyPayAmount')" label="老买家支付金额" prop="oldBuyPayAmount">
          <el-input v-model="queryParams.oldBuyPayAmountMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.oldBuyPayAmountMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('payConversionRate')" label="支付转化率" prop="payConversionRate">
          <el-input v-model="queryParams.payConversionRateMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.payConversionRateMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('havePayGoodsNumber')" label="有支付商品数" prop="havePayGoodsNumber">
          <el-input v-model="queryParams.havePayGoodsNumberMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.havePayGoodsNumberMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('haveVisitGoodsNumber')" label="有访问商品数" prop="haveVisitGoodsNumber">
          <el-input v-model="queryParams.haveVisitGoodsNumberMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.haveVisitGoodsNumberMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>

        <el-form-item v-if="isShowSearch('customerOrderPrice')" label="客单价" prop="customerOrderPrice">
          <el-input v-model="queryParams.customerOrderPriceMin" placeholder="请输入" style="width: 150px;"></el-input>
          <span> - </span>
          <el-input v-model="queryParams.customerOrderPriceMax" placeholder="请输入" style="width: 150px;"></el-input>
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery(true)">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          @click="handleUpload"
        >上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="showSetting = true">
          动态表头
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="getSearchByDate(1)">
          日
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="getSearchByDate(2)">
          周
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="getSearchByDate(3)">
          月
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="getSearchByDate(4)">
          年
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div ref="divTable" >
      <el-table :height="showSearch?'55vh':'62vh'" :key="dataTotal" :summary-method="getScoreSummaries"  :show-summary="showSummary" v-loading="loading" :data="storeIndicatorsList" @selection-change="handleSelectionChange" @sort-change='sortChange'>
        <el-table-column
          width="120px"
          v-for="column in getvisibleColumns()"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :show-overflow-tooltip='true'
          sortable='custom'>
          <template slot="header" slot-scope="scope">
            {{scope.column.label}}
            <el-tooltip v-if="column.tooltip" class="item" effect="dark" :content="column.content" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :pageRefs="this.$refs"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
    </div>
    <!-- 添加或修改店铺指标数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="店铺" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择店铺" clearable >
            <el-option
              v-for="item in storeList"
              :key="item.id"
              :label="item.storeAbbr"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="统计日期" prop="statDate">
          <el-date-picker clearable
            v-model="form.statDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择统计日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="成功退货退款金额" prop="successGoodsRefundAmount">
          <el-input v-model="form.successGoodsRefundAmount" placeholder="请输入成功退货退款金额" />
        </el-form-item>
        <el-form-item label="支付金额" prop="payAmount">
          <el-input v-model="form.payAmount" placeholder="请输入支付金额" />
        </el-form-item>
        <el-form-item label="分期支付金额" prop="stagesPayAmount">
          <el-input v-model="form.stagesPayAmount" placeholder="请输入分期支付金额" />
        </el-form-item>
        <el-form-item label="支付件数" prop="payQuantity">
          <el-input v-model="form.payQuantity" placeholder="请输入支付件数" />
        </el-form-item>
        <el-form-item label="商品加购人数" prop="goodsAddPeopleNumber">
          <el-input v-model="form.goodsAddPeopleNumber" placeholder="请输入商品加购人数" />
        </el-form-item>
        <el-form-item label="商品加购件数" prop="goodsAddQuantity">
          <el-input v-model="form.goodsAddQuantity" placeholder="请输入商品加购件数" />
        </el-form-item>
        <el-form-item label="商品浏览量" prop="goodsPageViewNumber">
          <el-input v-model="form.goodsPageViewNumber" placeholder="请输入商品浏览量" />
        </el-form-item>
        <el-form-item label="商品访客数" prop="goodsVisitorNumber">
          <el-input v-model="form.goodsVisitorNumber" placeholder="请输入商品访客数" />
        </el-form-item>
        <el-form-item label="商品微详情访客数" prop="goodsDetailVisitorNumber">
          <el-input v-model="form.goodsDetailVisitorNumber" placeholder="请输入商品微详情访客数" />
        </el-form-item>
        <el-form-item label="商品收藏人数" prop="goodsCollectPeopleNumber">
          <el-input v-model="form.goodsCollectPeopleNumber" placeholder="请输入商品收藏人数" />
        </el-form-item>
        <el-form-item label="商品平均停留时长" prop="goodsStopDuration">
          <el-input v-model="form.goodsStopDuration" placeholder="请输入商品平均停留时长" />
        </el-form-item>
        <el-form-item label="下单买家数" prop="placeOrderBuyNumber">
          <el-input v-model="form.placeOrderBuyNumber" placeholder="请输入下单买家数" />
        </el-form-item>
        <el-form-item label="支付买家数" prop="payBuyNumber">
          <el-input v-model="form.payBuyNumber" placeholder="请输入支付买家数" />
        </el-form-item>
        <el-form-item label="下单转化率" prop="placeOrderConversionRate">
          <el-input v-model="form.placeOrderConversionRate" placeholder="请输入下单转化率" />
        </el-form-item>
        <el-form-item label="商品详情页跳出率" prop="goodsDetailDapRate">
          <el-input v-model="form.goodsDetailDapRate" placeholder="请输入商品详情页跳出率" />
        </el-form-item>
        <el-form-item label="下单金额" prop="placeOrderAmount">
          <el-input v-model="form.placeOrderAmount" placeholder="请输入下单金额" />
        </el-form-item>
        <el-form-item label="访问收藏转化率" prop="collectConversionRate">
          <el-input v-model="form.collectConversionRate" placeholder="请输入访问收藏转化率" />
        </el-form-item>
        <el-form-item label="访问加购转化率" prop="addPurchaseConversionRate">
          <el-input v-model="form.addPurchaseConversionRate" placeholder="请输入访问加购转化率" />
        </el-form-item>
        <el-form-item label="支付老买家数" prop="payOldBuyNumber">
          <el-input v-model="form.payOldBuyNumber" placeholder="请输入支付老买家数" />
        </el-form-item>
        <el-form-item label="老买家支付金额" prop="oldBuyPayAmount">
          <el-input v-model="form.oldBuyPayAmount" placeholder="请输入老买家支付金额" />
        </el-form-item>
        <el-form-item label="支付转化率" prop="payConversionRate">
          <el-input v-model="form.payConversionRate" placeholder="请输入支付转化率" />
        </el-form-item>
        <el-form-item label="支付新买家数" prop="payNewBuyNumber">
          <el-input v-model="form.payNewBuyNumber" placeholder="请输入支付新买家数" />
        </el-form-item>
        <el-form-item label="有支付商品数" prop="havePayGoodsNumber">
          <el-input v-model="form.havePayGoodsNumber" placeholder="请输入有支付商品数" />
        </el-form-item>
        <el-form-item label="下单件数" prop="placeOrderNumber">
          <el-input v-model="form.placeOrderNumber" placeholder="请输入下单件数" />
        </el-form-item>
        <el-form-item label="有访问商品数" prop="haveVisitGoodsNumber">
          <el-input v-model="form.haveVisitGoodsNumber" placeholder="请输入有访问商品数" />
        </el-form-item>
        <el-form-item label="客单价" prop="customerOrderPrice">
          <el-input v-model="form.customerOrderPrice" placeholder="请输入客单价" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--文件上传弹窗-->
    <el-dialog
      title="上传数据"
      :visible.sync="uploadVisible"
      width="30%"
      >
      <div>
        <el-row>
          店铺:
          <el-select v-model="uploadData.storeId" filterable placeholder="请选择店铺" clearable >
            <el-option
              v-for="item in storeList"
              :key="item.id"
              :label="item.storeAbbr"
              :value="item.id">
            </el-option>
          </el-select>
        </el-row>

        <el-row style="margin-top: 10px">
          日期:
          <el-date-picker
            v-model="uploadData.selectDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期">
          </el-date-picker>
        </el-row>

        <el-row style="margin-top: 10px">
          <el-upload
            class="upload-demo"
            :headers="{
          'Authorization': 'Bearer ' + gainGetToken()
        }"
            :disabled="uploadData.storeId===null||uploadData.selectDate==null"
            ref="upload"
            :auto-upload="false"
            :action=uploadAction
            :data="uploadData"
            :on-change="handleChange"
            :on-progress="handleLoading"
            :on-success="handleUploadMessage"
            :file-list="fileList"
            :limit="1"
            drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-row>
      </div>
    </el-dialog>

    <!-- 表头设置弹窗-->
    <el-dialog title="动态表头设置" :visible.sync="showSetting">
      <el-button type="primary" icon="el-icon-delete" @click="cancelSelectedHeaders">取消选择</el-button>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>店铺指标</span>
        </div>
        <el-row>
          <el-checkbox-group v-model="selectedHeaders">
            <el-col :span="6" v-for="column in allColumns" :key="column.prop">
              <el-checkbox :label="column.prop"> {{ column.label }}</el-checkbox>
            </el-col>
          </el-checkbox-group>
        </el-row>
      </el-card>

      <span slot="footer">
        <el-button @click="showSetting = false">取消</el-button>
        <el-button type="primary" @click="saveSettings">保存</el-button>
      </span>
    </el-dialog>

    <!--搜索条件弹窗-->
    <el-dialog title="搜索条件配置" :visible.sync="showSelectSetting">
      <el-row>
        <el-checkbox-group v-model="selectedItems">
          <el-col :span="6" v-for="item in allSelectItems" :key="item.prop">
            <el-checkbox
              :label="item.prop"
            >
              {{ item.label }}
            </el-checkbox>
          </el-col>
        </el-checkbox-group>
      </el-row>
      <span slot="footer">
        <el-button @click="showSelectSetting = false">取消</el-button>
        <el-button type="primary" @click="saveSelectSettings">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStoreIndicators,
  getStoreIndicators,
  delStoreIndicators,
  addStoreIndicators,
  updateStoreIndicators,
  exportExcel,
  getStoreList, allList
} from "@/api/business/storeIndicators";
import ResizeMixin from "@/layout/mixin/ResizeHandler";
import {getToken} from "@/utils/auth";
import {getStoreMgmt} from "@/api/business/storeMgmt";
import SparkMD5 from "spark-md5";
import {parseTime} from "../../../utils/basic";

export default {
  name: "StoreIndicators",
  mixins: [ResizeMixin],
  data() {
    return {
      // div高度
      divHeight: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 店铺指标数据表格数据
      storeIndicatorsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName:null,
        statDateRange:null,
        statDateStart:null,
        statDateEnd:null,
        successGoodsRefundAmountMin:null,
        successGoodsRefundAmountMax:null,
        payAmountMin:null,
        payAmountMax:null,
        payQuantityMin:null,
        payQuantityMax:null,
        goodsAddPeopleNumberMin:null,
        goodsAddPeopleNumberMax:null,
        goodsAddQuantityMin:null,
        goodsAddQuantityMax:null,
        goodsVisitorNumberMin:null,
        goodsVisitorNumberMax:null,
        goodsCollectPeopleNumberMin:null,
        goodsCollectPeopleNumberMax:null,
        goodsStopDurationMin:null,
        goodsStopDurationMax:null,
        payBuyNumberMin:null,
        payBuyNumberMax:null,
        payOldBuyNumberMin:null,
        payOldBuyNumberMax:null,
        oldBuyPayAmountMin:null,
        oldBuyPayAmountMax:null,
        havePayGoodsNumberMin:null,
        havePayGoodsNumberMax:null,
        haveVisitGoodsNumberMin:null,
        haveVisitGoodsNumberMax:null,
        customerOrderPriceMin:null,
        customerOrderPriceMax:null,
        goodsDetailDapRateMin:null,
        goodsDetailDapRateMax:null,
        payConversionRateMin:null,
        payConversionRateMax:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
      },
      uploadVisible:false,
      uploadAction:"",
      //上传文件
      fileList:[],
      //店铺列表
      storeList:[],
      uploadData: { storeId: null, selectDate: null,fileHash: null},
      uploadLoad:null,
      showSetting: false,
      // 选中的表头
      selectedHeaders: [],
      // 全部可用列配置
      allColumns: [
        { label: '店铺', prop: 'storeName', visible: true },
        { label: '统计日期', prop: 'statDate', visible: true },
        { label: '成功退货退款金额', prop: 'successGoodsRefundAmount', visible: true },
        { label: '支付金额', prop: 'payAmount', visible: true },
        { label: '分期支付金额', prop: 'stagesPayAmount', visible: true },
        { label: '支付件数', prop: 'payQuantity', visible: true },
        { label: '商品加购人数', prop: 'goodsAddPeopleNumber', visible: false },
        { label: '商品加购件数', prop: 'goodsAddQuantity', visible: false },
        { label: '商品浏览量', prop: 'goodsPageViewNumber', visible: false },
        { label: '商品访客数', prop: 'goodsVisitorNumber', visible: false },
        { label: '商品微详情访客数', prop: 'goodsDetailVisitorNumber', visible: false },
        { label: '商品收藏人数', prop: 'goodsCollectPeopleNumber', visible: false },
        { label: '商品平均停留时长', prop: 'goodsStopDuration', visible: false, tooltip: true, content: '商品平均停留时长*商品访客数的合计/商品访客数的合计' },
        { label: '下单买家数', prop: 'placeOrderBuyNumber', visible: false },
        { label: '支付买家数', prop: 'payBuyNumber', visible: false },
        { label: '下单转化率', prop: 'placeOrderConversionRate', visible: false, tooltip: true, content: '下单买家数/商品访客数' },
        { label: '商品详情页跳出率', prop: 'goodsDetailDapRate', visible: false, tooltip: true, content: '商品详情页跳出率*商品访客数的合计/商品访客数的合计' },
        { label: '下单金额', prop: 'placeOrderAmount', visible: false },
        { label: '访问收藏转化率', prop: 'collectConversionRate', visible: false, tooltip: true, content: '商品收藏人数/商品访客数' },
        { label: '访问加购转化率', prop: 'addPurchaseConversionRate', visible: false, tooltip: true, content: '商品加购人数/商品访客数' },
        { label: '支付老买家数', prop: 'payOldBuyNumber', visible: false },
        { label: '老买家支付金额', prop: 'oldBuyPayAmount', visible: false },
        { label: '支付转化率', prop: 'payConversionRate', visible: false, tooltip: true, content: '支付买家数/商品访客数' },
        { label: '支付新买家数', prop: 'payNewBuyNumber', visible: false },
        { label: '有支付商品数', prop: 'havePayGoodsNumber', visible: false },
        { label: '下单件数', prop: 'placeOrderNumber', visible: false },
        { label: '有访问商品数', prop: 'haveVisitGoodsNumber', visible: false },
        { label: '客单价', prop: 'customerOrderPrice', visible: false, tooltip: true, content: '支付金额/支付买家数' }
      ],
      //汇总数据
      collectData:{
        statDateStart:null,
        statDateEnd:null,
        successGoodsRefundAmount:0,
        payAmount:0,
        stagesPayAmount:0,
        payQuantity:0,
        goodsAddPeopleNumber:0,
        goodsAddQuantity:0,
        goodsPageViewNumber:0,
        goodsVisitorNumber:0,
        goodsDetailVisitorNumber:0,
        goodsCollectPeopleNumber:0,
        goodsStopDuration:0,
        placeOrderBuyNumber:0,
        payBuyNumber:0,
        placeOrderConversionRate:0,
        goodsDetailDapRate:0,
        placeOrderAmount:0,
        collectConversionRate:0,
        addPurchaseConversionRate:0,
        payOldBuyNumber:0,
        oldBuyPayAmount:0,
        payConversionRate:0,
        payNewBuyNumber:0,
        havePayGoodsNumber:0,
        placeOrderNumber:0,
        haveVisitGoodsNumber:0,
        customerOrderPrice:0,
      },
      //展示合计
      showSummary:false,
      //控制刷新表格
      dataTotal:0,
      //搜索条件集合
      allSelectItems: [
        {label: '店铺', prop: 'storeName'},
        {label: '统计日期', prop: 'statDate'},
        {label: '成功退货退款金额', prop: 'successGoodsRefundAmount'},
        {label: '支付金额', prop: 'payAmount'},
        {label: '支付件数', prop: 'payQuantity'},
        {label: '商品加购人数', prop: 'goodsAddPeopleNumber'},
        {label: '商品加购件数', prop: 'goodsAddQuantity'},
        {label: '商品访客数', prop: 'goodsVisitorNumber'},
        {label: '商品收藏人数', prop: 'goodsCollectPeopleNumber'},
        {label: '商品平均停留时长', prop: 'goodsStopDuration'},
        {label: '支付买家数', prop: 'payBuyNumber'},
        {label: '商品详情页跳出率', prop: 'goodsDetailDapRate'},
        {label: '支付老买家数', prop: 'payOldBuyNumber'},
        {label: '老买家支付金额', prop: 'oldBuyPayAmount'},
        {label: '支付转化率', prop: 'payConversionRate'},
        {label: '有支付商品数', prop: 'havePayGoodsNumber'},
        {label: '有访问商品数', prop: 'haveVisitGoodsNumber'},
        {label: '客单价', prop: 'customerOrderPrice'}
      ],
      showSelectSetting: false,
      // 选中的表单项
      selectedItems: ['statDate'],
    };
  },
  created() {
    this.getList();
    this.getStoreList();
  },
  mounted() {
    this.loadSettings()
  },
  computed: {
    // 可见列计算属性
    visibleColumns() {
      //返回allColumns中visible为true的项。
      return this.allColumns.filter(column =>
        this.selectedHeaders.includes(column.prop)
      )
    }
  },
  methods: {
    //表头选择按照选择顺序展示
    getvisibleColumns(){
      let list = []
      this.selectedHeaders.map(i => {
        this.visibleColumns.map(x => {
          if (x.prop === i){
            list.push(x)
          }
        })
      })
      return list
    },
    //日期条件筛选汇总
    getSearchByDate(item){
      const today = new Date();
      if (item===1){
        // 获取昨天的日期
        const yesterday = new Date(today);
        yesterday.setDate(today.getDate() - 1);

        const yesterdayFormat=this.formatDate(yesterday);

        this.queryParams.statDateRange=[yesterdayFormat,  yesterdayFormat]
      }else if (item===2){
        // 获取当前日期是本周的第几天（0=周日，1=周一，...，6=周六）
        const currentDayOfWeek = today.getDay();

        // 计算上周周一的日期
        const lastMonday = new Date(today);
        lastMonday.setDate(today.getDate() - currentDayOfWeek - 6); // 减去当前星期几和 6 天

        // 计算上周周日的日期
        const lastSunday = new Date(today);
        lastSunday.setDate(today.getDate() - currentDayOfWeek); // 减去当前星期几

        const lastMondayFormat=this.formatDate(lastMonday)
        const lastSundayFormat=this.formatDate(lastSunday)

        this.queryParams.statDateRange=[lastMondayFormat,  lastSundayFormat]
      }else if (item===3){
        // 获取上个月的最后一天
        const lastDayOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0);

        // 获取上个月的第一天
        const firstDayOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);

        const firstDayFormat=this.formatDate(firstDayOfLastMonth)
        const lastDayFormat=this.formatDate(lastDayOfLastMonth)

        this.queryParams.statDateRange=[firstDayFormat,  lastDayFormat]
      }else if (item===4){
        // 获取一年前的日期
        const oneYearAgo = new Date(today);
        oneYearAgo.setFullYear(today.getFullYear() - 1);

        const lastYearFormat=this.formatDate(oneYearAgo)
        const todayFormat=this.formatDate(today)

        this.queryParams.statDateRange=[lastYearFormat,  todayFormat]
      }

      this.handleQuery(true)
    },
    //格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    //计算汇总数据
    getCollectData(){
      //条件查询不分页数据
      allList(this.queryParams).then(response => {
        const data = response.data;

        if (data.length>0){
          //计算累加数据
          this.collectData = this.sumObject(response.data)
          //统计日期
          this.collectData.statDateStart=data[0].statDate;
          this.collectData.statDateEnd=data[data.length-1].statDate;

          //初始化
          this.collectData = {...this.collectData, ...{ goodsStopDuration: 0, placeOrderConversionRate: 0, goodsDetailDapRate: 0, collectConversionRate: 0, addPurchaseConversionRate: 0, payConversionRate: 0, customerOrderPrice: 0  }}

          //商品平均停留时长=筛选时间段内每天的商品平均停留时长*商品访客数的合计/筛选时间段内的商品访客数总数
          this.collectData.goodsStopDuration=this.collectData.goodsStopDurationA/this.collectData.goodsVisitorNumber;
          //下单转化率=下单买家数/商品访客数
          this.collectData.placeOrderConversionRate=this.collectData.placeOrderBuyNumber/this.collectData.goodsVisitorNumber;
          //商品详情页跳出率=每天的商品详情页跳出率*商品访客数的合计/商品访客数的合计
          this.collectData.goodsDetailDapRate=this.collectData.goodsDetailDapRateA/this.collectData.goodsVisitorNumber;
          //访问收藏转化率=商品收藏人数/商品访客数
          this.collectData.collectConversionRate=this.collectData.goodsCollectPeopleNumber/this.collectData.goodsVisitorNumber;
          //访问加购转化率=商品加购人数/商品访客数
          this.collectData.addPurchaseConversionRate=this.collectData.goodsAddPeopleNumber/this.collectData.goodsVisitorNumber;
          //支付转化率=支付买家数/商品访客数
          this.collectData.payConversionRate=this.collectData.payBuyNumber/this.collectData.goodsVisitorNumber;
          //客单价=支付金额/支付买家数
          this.collectData.customerOrderPrice=this.collectData.payAmount/this.collectData.payBuyNumber;
        }

        //展示合计
        this.showSummary=true
        this.dataTotal = new Date().getTime()
      });
    },
    //计算累加数据
    sumObject(list) {
      let goodsStopDurationA = 0
      let goodsDetailDapRateA = 0
      list.map(item => {
        goodsStopDurationA += parseFloat(item['goodsStopDuration']) * parseFloat(item['goodsVisitorNumber'])
        goodsDetailDapRateA += parseFloat(item['goodsDetailDapRate'].replace('%', ''))/100 * parseFloat(item['goodsVisitorNumber'])
      })
      return list.reduce((acc, item) => {
        // 遍历当前对象的每个字段
        for (const key in item) {
          if (!(['addPurchaseConversionRate','collectConversionRate','createBy','createTime','fileId','storeName','storeId','statDate','placeOrderConversionRate','payConversionRate','id','goodsDetailDapRate'].includes(key))){
            // 如果累加器对象中还没有这个字段，初始化为0
            if (!acc.hasOwnProperty(key)) { acc[key] = 0; }
            // 累加当前字段的值
            acc[key] += item[key];
          }
        }
        return {...acc, ...{goodsStopDurationA: goodsStopDurationA, goodsDetailDapRateA: goodsDetailDapRateA}};
      }, {});
      // 初始值为一个空对象
    },
    //返回表格合计数据
    getScoreSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (column.property==='statDate'){
          sums[index]=this.collectData.statDateStart+'至'+this.collectData.statDateEnd
        }else if (this.selectedHeaders.includes(column.property)){
          if ((['placeOrderConversionRate','goodsDetailDapRate','collectConversionRate','addPurchaseConversionRate','payConversionRate'].includes(column.property))){
            sums[index]=(parseFloat(this.collectData[column.property])*100).toFixed(2)+'%'
          }else {
            sums[index]=parseFloat(this.collectData[column.property]).toFixed(2)
          }
        }
      })
      sums[0] = '合计'
      return sums
    },
    //后端全页面动态排序
    sortChange(column){
      this.queryParams.order=null
      this.queryParams.prop=null
      console.log(column,"排序")
      if (column.order==="ascending"){
        this.queryParams.order="asc"
      }else if (column.order==="descending"){
        this.queryParams.order="desc"
      }
      //转换驼峰命名
      const prop= column.prop.replace(/([A-Z])/g, function(match) { return '_' + match.toLowerCase(); })
      this.queryParams.prop=prop;

      this.getList()
    },
    //统计日期组件改变值
    statDateChange(){
      this.queryParams.statDateStart=this.queryParams.statDateRange[0]
      this.queryParams.statDateEnd=this.queryParams.statDateRange[1]
    },
    parseTime,
    /** 查询店铺指标数据列表 */
    getList() {
      this.loading = true;
      listStoreIndicators(this.queryParams).then(response => {
        this.storeIndicatorsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        storeName:null,
        statDateRange:null,
        statDateStart:null,
        statDateEnd:null,
        successGoodsRefundAmountMin:null,
        successGoodsRefundAmountMax:null,
        payAmountMin:null,
        payAmountMax:null,
        payQuantityMin:null,
        payQuantityMax:null,
        goodsAddPeopleNumberMin:null,
        goodsAddPeopleNumberMax:null,
        goodsAddQuantityMin:null,
        goodsAddQuantityMax:null,
        goodsVisitorNumberMin:null,
        goodsVisitorNumberMax:null,
        goodsCollectPeopleNumberMin:null,
        goodsCollectPeopleNumberMax:null,
        goodsStopDurationMin:null,
        goodsStopDurationMax:null,
        payBuyNumberMin:null,
        payBuyNumberMax:null,
        payOldBuyNumberMin:null,
        payOldBuyNumberMax:null,
        oldBuyPayAmountMin:null,
        oldBuyPayAmountMax:null,
        havePayGoodsNumberMin:null,
        havePayGoodsNumberMax:null,
        haveVisitGoodsNumberMin:null,
        haveVisitGoodsNumberMax:null,
        customerOrderPriceMin:null,
        customerOrderPriceMax:null,
        goodsDetailDapRateMin:null,
        goodsDetailDapRateMax:null,
        payConversionRateMin:null,
        payConversionRateMax:null,
      };
      this.$resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery(flag) {
      this.queryParams.pageNum = 1;
      this.getList();

      //搜索展示合计，重置关闭合计
      if (flag){
        //计算汇总合计
        this.getCollectData();
      }else {
        this.showSummary=false
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$resetForm("queryForm");
      this.queryParams.storeName=null
      this.queryParams.statDateRange=null
      this.queryParams.statDateStart=null
      this.queryParams.statDateEnd=null
      this.queryParams.successGoodsRefundAmountMin=null
      this.queryParams.successGoodsRefundAmountMax=null
      this.queryParams.payAmountMin=null
      this.queryParams.payAmountMax=null
      this.queryParams.payQuantityMin=null
      this.queryParams.payQuantityMax=null
      this.queryParams.goodsAddPeopleNumberMin=null
      this.queryParams.goodsAddPeopleNumberMax=null
      this.queryParams.goodsAddQuantityMin=null
      this.queryParams.goodsAddQuantityMax=null
      this.queryParams.goodsVisitorNumberMin=null
      this.queryParams.goodsVisitorNumberMax=null
      this.queryParams.goodsCollectPeopleNumberMin=null
      this.queryParams.goodsCollectPeopleNumberMax=null
      this.queryParams.goodsStopDurationMin=null
      this.queryParams.goodsStopDurationMax=null
      this.queryParams.payBuyNumberMin=null
      this.queryParams.payBuyNumberMax=null
      this.queryParams.payOldBuyNumberMin=null
      this.queryParams.payOldBuyNumberMax=null
      this.queryParams.oldBuyPayAmountMin=null
      this.queryParams.oldBuyPayAmountMax=null
      this.queryParams.havePayGoodsNumberMin=null
      this.queryParams.havePayGoodsNumberMax=null
      this.queryParams.haveVisitGoodsNumberMin=null
      this.queryParams.haveVisitGoodsNumberMax=null
      this.queryParams.customerOrderPriceMin=null
      this.queryParams.customerOrderPriceMax=null
      this.queryParams.goodsDetailDapRateMin=null
      this.queryParams.goodsDetailDapRateMax=null
      this.queryParams.payConversionRateMin=null
      this.queryParams.payConversionRateMax=null
      this.handleQuery(false);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加店铺指标数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStoreIndicators(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改店铺指标数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStoreIndicators(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStoreIndicators(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除店铺指标数据编号为"' + ids + '"的数据项？').then(function() {
        return delStoreIndicators(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      exportExcel(this.queryParams)
    },
    //获取所负责的店铺列表
    getStoreList(){
      getStoreList().then(response => {
        this.storeList=response.data;
      })
    },
    //上传按钮
    handleUpload(){
      this.uploadAction=process.env.VUE_APP_BASE_API+"/business/storeIndicators/uploadData"
      this.fileList=[];
      this.uploadData.storeId=null;
      this.uploadData.selectDate=null;
      this.uploadData.fileHash=null;
      this.uploadVisible = true;
    },
    //上传校验
     async handleChange(file) {
       //文件上传完成
       if (file.response){
         return false
       }

      let fileStore = this.getSpecificBracketedContent(file.name, 1);
      let fileDate = this.getSpecificBracketedContent(file.name, 2);

      let selectStoreName;
      await getStoreMgmt(this.uploadData.storeId).then(response => {
        selectStoreName=response.data.storeName
      })

      //校验文件店铺名和日期
      if (selectStoreName===fileStore&&this.uploadData.selectDate===this.conversionDate(fileDate)){

        //获取文件哈希值校验文件是否已上传
        this.getFileHash(file).then(res => {
          this.uploadData.fileHash=res
          //上传
          this.$refs.upload.submit();
        })
      }else {
        this.$message({
          message: '店铺和日期与上传文件不符，请核实',
          type: 'warning'
        });
      }
    },
    //上传加载
    handleLoading(){
      this.uploadLoad = this.$loading({
        lock: true,
        text: '数据上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    //文件上传后的回调
    handleUploadMessage(res, file){
      //清空文件集合
      this.$refs.upload.clearFiles();
      this.uploadLoad.close();
      console.log("文件上传后的回调",res)
      if (res.code === 200) {
        this.$message({
          showClose: true,
          message: '数据上传成功',
          type: 'success'
        });
        this.uploadVisible = false;
        this.getList()
      }else if (res.code === 500) {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        });
      }
    },
    //文件上传获取token
    gainGetToken(){
      return getToken()
    },
     //获取上传文件名【】中内容
    getSpecificBracketedContent(str, pairIndex) {
      const regex = /【(.*?)】/g;
      let match;
      let content = null;

      for (let i = 0; i < pairIndex; i++) {
        match = regex.exec(str);
        if (!match) {
          break; // 如果没有足够的匹配项，退出循环
        }
        // 对于我们关心的那一对，保存其内容
        if (i === pairIndex - 1) {
          content = match[1];
        }
      }

      return content;
    },
    //获取文件哈希值
    getFileHash(file) {
      return new Promise((resolve, reject) => {
        let fileHash;
        const fileReader = new FileReader();
        const spark = new SparkMD5.ArrayBuffer();

        // 获取文件二进制数据
        fileReader.readAsArrayBuffer(file.raw);

        fileReader.onload = (e) => {
          try {
            spark.append(e.target.result);
            fileHash = spark.end();
            resolve(fileHash); // 使用resolve返回哈希值
          } catch (error) {
            reject(error); // 在发生错误时拒绝Promise
          }
        };

        fileReader.onerror = (error) => {
          reject(error); // 处理文件读取错误
        };
      });
    },
    // 保存设置
    saveSettings() {
      // 更新列显示状态
      this.allColumns.forEach(column => {
        column.visible = this.selectedHeaders.includes(column.prop)
      })

      // 保存到本地存储
      localStorage.setItem('storeTableHeaders', JSON.stringify(this.selectedHeaders))
      this.showSetting = false
    },
    // 加载保存的设置
    loadSettings() {
      const saved = localStorage.getItem('storeTableHeaders')
      if (saved) {
        this.selectedHeaders = JSON.parse(saved)
      } else {
        // 默认选中可见的列
        this.selectedHeaders = this.allColumns
          .filter(column => column.visible)
          .map(column => column.prop)
      }
    },
    //转换日期格式
    conversionDate(dateStr) {
      // 正则表达式匹配不同格式的日期字符串
      const regex = /(\d{4})[/-]?(\d{1,2})[/-]?(\d{1,2})/;
      const match = dateStr.match(regex);

      if (match) {
        const [, year, month, day] = match;

        // 确保月份和日期都是两位数
        const formattedMonth = String(parseInt(month, 10)).padStart(2, '0');
        const formattedDay = String(parseInt(day, 10)).padStart(2, '0');

        // 返回格式化后的日期字符串
        return `${year}-${formattedMonth}-${formattedDay}`;
      } else {
        this.$message({
          message: '文件日期格式错误',
          type: 'warning'
        });
      }
    },
    //保存选择的动态搜索条件
    saveSelectSettings(){
      this.showSelectSetting=false
    },
    //是否展示搜索条件
    isShowSearch(prop) {
      return this.selectedItems.includes(prop);
    },
    //取消动态表头的选择
    cancelSelectedHeaders(){
      this.selectedHeaders=[]
    }
  }
};
</script>
